package com.huawei.app.demo.fragment;

import java.io.File;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huawei.app.demo.AppConstants;
import com.huawei.app.demo.MsgHandler;
import com.huawei.app.demo.R;
import com.huawei.app.demo.util.LogUtils;
import com.huawei.app.httpapi.HttpApiResult;
import com.huawei.app.httpapi.IdeaHubHttpApiUtils;
import com.huawei.app.httpapi.MsgRspCallback;
import com.huawei.app.httpapi.ThreadPools;

/**
 * HTTP API
 *
 * @since 2021-01-20
 */
public class HttpApiFragment extends CustomFragment {

    private static final String TAG = HttpApiFragment.class.getSimpleName();

    private Context context;
    private View rootView;

    private CheckBox toogleTopAppPkg;
    private FaceDetectionTask faceDetectionTask;
    private MsgRspCallback msgCallback = new FaceDetectionMsgCallback();
    private boolean initDataFinish = false;

    @Override
    public String getTitle() {
        return "HTTP API";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (this.rootView != null) {
            return rootView;
        }
        this.context = getContext();
        this.rootView = inflater.inflate(R.layout.fragment_http_api, container, false);

        // init view
        Button goToSleep = rootView.findViewById(R.id.goToSleep);
        Button rebootDevice = rootView.findViewById(R.id.rebootDevice);
        Button shutdownDevice = rootView.findViewById(R.id.shutdownDevice);
        Button installApk = rootView.findViewById(R.id.installApk);
        this.toogleTopAppPkg = rootView.findViewById(R.id.toogleTopAppPkg);
        Button startFaceDetection = rootView.findViewById(R.id.startFaceDetection);
        Button stopFaceDetection = rootView.findViewById(R.id.stopFaceDetection);

        // init event
        goToSleep.setOnClickListener(this);
        rebootDevice.setOnClickListener(this);
        shutdownDevice.setOnClickListener(this);
        installApk.setOnClickListener(this);
        toogleTopAppPkg.setOnClickListener(this);
        startFaceDetection.setOnClickListener(this);
        stopFaceDetection.setOnClickListener(this);

        return rootView;
    }

    /**
     * 初始化组件状态(例如Checkbox选中状态)
     */
    @Override
    public void initViewStatus() {
        int delayTime = 500;
        if (IdeaHubHttpApiUtils.getInstance().isLoginSuccess()) {
            delayTime = 0;
        }

        ThreadPools.schedule(new Runnable() {
            @Override
            public void run() {
                if (!IdeaHubHttpApiUtils.getInstance().isLoginSuccess()) {
                    return;
                }

                String pkgName = context.getPackageName();
                HttpApiResult apiResult = null;
                if (!initDataFinish) {
                    apiResult = IdeaHubHttpApiUtils.getInstance().setTopAppPkg(pkgName);
                    initDataFinish = apiResult.isSuccess();
                }

                boolean checked = false;
                apiResult = IdeaHubHttpApiUtils.getInstance().getTopAppPkg();
                if (pkgName.equals(apiResult.getData().getString("packageName"))) {
                    checked = true;
                }

                Message msg = Message.obtain();
                msg.what = MsgHandler.UPDATE_VIEW_CHECK_STATUS;
                msg.obj = new MsgHandler.UpdateViewCheckStatus(R.id.toogleTopAppPkg, checked, false);
                if (msgHandler != null) {
                    msgHandler.sendMessage(msg);
                }
            }
        }, delayTime, TimeUnit.MILLISECONDS);
    }

    @Override
    public void onResume() {
        super.onResume();
        initViewStatus();
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.goToSleep: {
                goToSleep();
                break;
            }
            case R.id.rebootDevice: {
                reboot();
                break;
            }
            case R.id.shutdownDevice: {
                shutdown();
                break;
            }
            case R.id.installApk : {
                installApk();
                break;
            }
            case R.id.toogleTopAppPkg: {
                toogleTopAppPkg();
                break;
            }
            case R.id.startFaceDetection: {
                startFaceDetection();
                break;
            }
            case R.id.stopFaceDetection: {
                stopFaceDetection();
                break;
            }
            default: {
                break;
            }
        }
    }

    /**
     * 休眠
     */
    public void goToSleep() {
        LogUtils.getInstance().i(TAG, "goToSleep begin.");

        ThreadPools.run(new Runnable(){
            @Override
            public void run() {
                try {
                    IdeaHubHttpApiUtils.getInstance().startSleep();
                    Thread.sleep(10000);
                    HttpApiFragment.this.wakeup();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        LogUtils.getInstance().i(TAG, "goToSleep end.");
    }

    /**
     * 唤醒屏幕
     */
    private void wakeup() {
        LogUtils.getInstance().i(TAG, "wakeup begin.");

        IdeaHubHttpApiUtils.getInstance().wakeUp();

        LogUtils.getInstance().i(TAG, "wakeup end.");
    }

    /**
     * 重启
     */
    public void reboot() {
        LogUtils.getInstance().i(TAG, "reboot begin.");

        ThreadPools.run(new Runnable(){
            @Override
            public void run() {
                try {
                    IdeaHubHttpApiUtils.getInstance().reboot();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        LogUtils.getInstance().i(TAG, "reboot end.");
    }

    /**
     * 关机
     */
    public void shutdown() {
        LogUtils.getInstance().i(TAG, "shutdown begin.");

        ThreadPools.run(new Runnable(){
            @Override
            public void run() {
                try {
                    IdeaHubHttpApiUtils.getInstance().powerDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        LogUtils.getInstance().i(TAG, "shutdown end.");
    }

    /**
     * 静默安装/升级APP
     */
    public void installApk() {
        LogUtils.getInstance().i(TAG, "installApk begin.");

        final String apkPath = "/sdcard/Download/app-demo.apk";
        File apkFile = new File(apkPath);
        if (!apkFile.exists()) {
            Toast.makeText(context, "apk file [" + apkPath + "] not found.", Toast.LENGTH_LONG).show();
            LogUtils.getInstance().e(TAG, "installApk failed, apk file not found.");
            return;
        }

        PackageManager pm = getActivity().getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (info == null) {
            Toast.makeText(context, "apk file [" + apkPath + "] parse failed.", Toast.LENGTH_LONG).show();
            LogUtils.getInstance().e(TAG, "installApk failed, apk file parse failed.");
            return;
        }

        String packageName = info.packageName;
        String activityName = info.activities[0].name;
        final String componentName = packageName + "/" + activityName;
        ThreadPools.run(new Runnable() {
            @Override
            public void run() {
                LogUtils.getInstance().i(TAG, "installApk " + componentName);
                IdeaHubHttpApiUtils.getInstance().installApk(apkPath, componentName);
            }
        });

        LogUtils.getInstance().i(TAG, "installApk end.");
    }

    /**
     * 切换霸屏模式
     */
    public void toogleTopAppPkg() {
        LogUtils.getInstance().i(TAG, "toogleTopAppPkg begin.");

        setTopAppPkg(toogleTopAppPkg.isChecked());

        LogUtils.getInstance().i(TAG, "toogleTopAppPkg end.");
    }

    /**
     * 设置霸屏应用
     */
    private void setTopAppPkg(final boolean enableTopApp) {
        ThreadPools.run(new Runnable() {
            @Override
            public void run() {
                String tip = "取消霸屏模式";
                String pkgName = "";

                if (enableTopApp) {
                    pkgName = HttpApiFragment.this.getActivity().getPackageName();
                    tip = "设置霸屏模式[ " + pkgName + " ]";
                }

                // 修改之前先查询一次当前值
                HttpApiResult apiResult = IdeaHubHttpApiUtils.getInstance().getTopAppPkg();
                if (pkgName.equals(apiResult.getData().getString("packageName"))) {
                    return;
                }

                // 修改霸屏模式
                apiResult = IdeaHubHttpApiUtils.getInstance().setTopAppPkg(pkgName);
                if (apiResult.isSuccess()) {
                    LogUtils.getInstance().i(TAG, tip + " success.");
                } else {
                    LogUtils.getInstance().i(TAG, tip + " failed.");

                    Message msg = Message.obtain();
                    msg.what = MsgHandler.SHOW_TOAST;
                    msg.obj = tip + " 失败";
                    msgHandler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 开始人脸检测
     */
    private void startFaceDetection() {
        LogUtils.getInstance().i(TAG, "startFaceDetection begin.");
        if (this.faceDetectionTask != null) {
            LogUtils.getInstance().i(TAG, "startFaceDetection the face detection task has been running.");
            return;
        }

        this.faceDetectionTask = new FaceDetectionTask();
        ThreadPools.run(faceDetectionTask);

        LogUtils.getInstance().i(TAG, "startFaceDetection end.");
    }

    /**
     * 停止人脸检测
     */
    private void stopFaceDetection() {
        LogUtils.getInstance().i(TAG, "stopFaceDetection begin.");

        if (this.faceDetectionTask != null) {
            ThreadPools.run(new Runnable() {
                @Override
                public void run() {
                    IdeaHubHttpApiUtils.getInstance().stopFaceDetection();
                }
            });
            IdeaHubHttpApiUtils.getInstance().unregisterMsgCall(msgCallback);
            faceDetectionTask = null;

            Message msg = Message.obtain();
            msg.what = MsgHandler.CLEAR_FACE_DETECTION_RESULT;
            msgHandler.sendMessage(msg);
        }

        LogUtils.getInstance().i(TAG, "stopFaceDetection end.");
    }

    class FaceDetectionTask implements Runnable {

        @Override
        public void run() {
            IdeaHubHttpApiUtils.getInstance().registerMsgCall(msgCallback);

            HttpApiResult apiResult = IdeaHubHttpApiUtils.getInstance().startFaceDetection();
            if (!apiResult.isSuccess()) {
                LogUtils.getInstance().e(TAG, "startFaceDetection failed, apiResult is " + apiResult);

                Message msg = Message.obtain();
                msg.what = MsgHandler.SHOW_TOAST;
                msg.obj = "开始人脸检测失败.";
                msgHandler.sendMessage(msg);

                IdeaHubHttpApiUtils.getInstance().unregisterMsgCall(msgCallback);
                HttpApiFragment.this.faceDetectionTask = null;
                return;
            }
            LogUtils.getInstance().i(TAG, "startFaceDetection success.");
        }
    }

    class FaceDetectionMsgCallback implements MsgRspCallback {
        @Override
        public int getMsgId() {
            return AppConstants.MSG_AI_FACE_DETECTION_RESULT;
        }

        @Override
        public String getMsgName() {
            return "MSG_AI_FACE_DETECTION_RESULT";
        }

        @Override
        public void handleMsg(JSONObject msgObj) {
            if (msgObj == null) {
                return;
            }

            JSONArray detectionDataArray = msgObj.getJSONObject("msgData").getJSONArray("detectionData");
            LogUtils.getInstance().v(TAG, "find face detection data " + detectionDataArray);

            int faceId = -1;
            for (int i=0; i<detectionDataArray.size(); i++) {
                JSONObject detectionDataItem = detectionDataArray.getJSONObject(i);
                if (detectionDataItem.getInteger("status") != 1) {
                    // 状态1表示存在, 0表示消失
                    continue;
                }
                faceId = detectionDataItem.getInteger("id");
                break;
            }
            if (faceId == -1) {
                return;
            }
            LogUtils.getInstance().d(TAG, "get face id success, faceId = " + faceId);

            // 根据人脸识别id获取图像
            HttpApiResult apiResult = IdeaHubHttpApiUtils.getInstance().getFaceDetectionImg(faceId);
            if (!apiResult.isSuccess()) {
                LogUtils.getInstance().e(TAG, "getFaceDetectionImg failed, apiResult is " + apiResult);
                return;
            }

            // 更新人脸检测结果
            Message msg = Message.obtain();
            msg.what = MsgHandler.UPDATE_FACE_DETECTION_RESULT;
            msg.obj = (byte[])apiResult.getRawData();
            msgHandler.sendMessage(msg);
            LogUtils.getInstance().i(TAG, "send UPDATE_FACE_DETECTION_RESULT success, faceId = " + faceId);
        }
    }
}
